#!/bin/sh
#(c) Copyright Barry Kauler, Oct. 2011, bkhome.org
#2011 license GPL3 (see /usr/share/doc/legal)
#called via menu or autodetected when camera plugged in (via /usr/sbin/pupautodetect).
#usbutils optionally used if installed, lsusb accesses usb.ids to obtain device description.
#pupcamera is not a separate application, it is builtin to Woof so is in all builds
# -- it detects if gphoto (and deps) not installed and informs the user.

ROX_FILER=""
grep -q -m1 -i 'rox' /usr/local/bin/defaultfilemanager && ROX_FILER=yes

PIDOFMTP=`pidof mtpdevice`
[ "$PIDOFMTP" ] && exit # exits if mtpdevice process starts to tame udev rule 88-puppy-autodetect.rules

export TEXTDOMAIN=pupcamera
export OUTPUT_CHARSET=UTF-8

mkdir -p /mnt/camera1
mkdir -p /mnt/camera2
umount /mnt/camera1 2>/dev/null #precaution.
umount /mnt/camera2 2>/dev/null #precaution.

#as this app can be run from both menu and auto-detect plugging-in, kill any previous...
ALLPS="`busybox ps`"
OLDPIDS="`echo "$ALLPS" | grep 'gtkdialog' | grep 'PUPCAMERA_DLG' | tr -s ' ' | sed -e 's%^ %%' | cut -f 1 -d ' ' | tr '\n' ' '`"
kill $OLDPIDS 2>/dev/null

#find BUSNUM, DEVNUM...
BUSNUM=""; DEVNUM=""; PRODUCTDESC=""
if [ "$DEVPATH" ];then
 [ -e /sys${DEVPATH}/product ] && PRODUCTDESC="`cat /sys${DEVPATH}/product`"
 if [ "$DEVTYPE" = "usb_interface" ];then
  UPDEVPATH=$DEVPATH
  while [ "$UPDEVPATH" != "/" ];do
   UPDEVPATH="`dirname $UPDEVPATH`"
   case $UPDEVPATH in
    *usb*) #this is to avoid going too high.
     [ ! -e /sys${UPDEVPATH}/busnum ] && continue
     [ ! -e /sys${UPDEVPATH}/devnum ] && continue
     BUSNUM="00`cat /sys${UPDEVPATH}/busnum`"
     DEVNUM="00`cat /sys${UPDEVPATH}/devnum`"
     BUSNUM="`echo -n "$BUSNUM" | rev | cut -c 1,2,3 | rev`" #must be in 3-digit format, ex: 002
     DEVNUM="`echo -n "$DEVNUM" | rev | cut -c 1,2,3 | rev`" #must be in 3-digit format, ex: 012
     [ ! "$PRODUCTDESC" ] && [ -e /sys${UPDEVPATH}/product ] && PRODUCTDESC="`cat /sys${UPDEVPATH}/product`"
     break
    ;;
    *)
     break
    ;;
   esac
  done
 fi
fi

echo -n "" > /tmp/pupcamera_ports
CAMERAINFO=""
if [ "$BUSNUM" ];then
 
 #get product description from lsusb (usbutils pkg)...
 if which lsusb;then
  if [ "`lsusb --help 2>&1 | grep -i 'busybox'`" = "" ];then #want the full lsusb
   VENDORDESC="`lsusb -s ${BUSNUM}:${DEVNUM} | tr -s ' ' | cut -f 3-9 -d ':' | cut -f 2-99 -d ' '`"
  fi
 fi
 [ "$VENDORDESC" ] && VENDORDESC=" - <b>${VENDORDESC}</b>"
 CAMERAINFO="$(gettext 'Device detected:') <b>${PRODUCTDESC}</b>${VENDORDESC}" #$PRODUCTDESC is Linux id, while $VENDORDESC is vendor id
 CAMERAINFO_PORT="$(gettext 'Usb port:') ${BUSNUM},${DEVNUM}"
 echo "usb:${BUSNUM},${DEVNUM}" >> /tmp/pupcamera_ports
fi

PROBEINFO=""
if [ "`which gphoto2`" ];then
 GPHOTOPROBE="`gphoto2 --auto-detect | tr -s ' ' | tail -n +3`"
 if [ "$GPHOTOPROBE" ];then
  PROBEINFO="$(gettext "gphoto2 probe:") ${GPHOTOPROBE}"
  PROBEPORTS="`echo "$GPHOTOPROBE" | sed -e 's% *$%%' | rev | cut -f 1 -d ' ' | rev`"
  echo "$PROBEPORTS" >> /tmp/pupcamera_ports
 else
  if [ -s /tmp/pupcamera_ports ];then
   PROBEINFO="<b>$(gettext "No device is detected.")</b>
$(gettext "It means that the Gphoto software in puppy does not recognise your device. (But, you can try, click the <i>Open</i> button)")"
  else
   PROBEINFO="<b>$(gettext "No device is detected.")</b>
$(gettext "It means that the Gphoto software in puppy does not recognise your device.")"
  fi
 fi
else
 #gphoto (and deps) not installed...
 PROBEINFO="<b>$(gettext "The 'gphoto' application is not installed.")</b>
$(gettext "That means PupCamera cannot access the photos on a digital camera / cellphone. Please run the Puppy Package Manager (see 'install' icon on desktop) to install 'gphotofs' and it's dependencies.")"
 echo -n "" > /tmp/pupcamera_ports #remove button.
fi

if [ "`which gphotofs`" = "" ]; then #111015
 PROBEINFO="<b>$(gettext "The 'gphotofs' application is not installed.")</b>
$(gettext "That means PupCamera cannot access the photos on a digital camera / cellphone. Please run the Puppy Package Manager (see 'install' icon on desktop) to install 'gphotofs' and it's dependencies.")"
fi

func_splash(){
	case $1 in
		1)SMSG="$(gettext 'Please wait...')";;
		2)C1=`ls /mnt/camera1`;C2=`ls /mnt/camera2`
			if [ -z "$C1" ] && [ -z "$C2" ];then
				SMSG="$(gettext 'Device is closed')"
			else
				SMSG="$(gettext 'You may have to close your file manager to close the device correctly')"
			fi;;
	esac
	/usr/lib/gtkdialog/box_splash -placement center -timeout 5 -fontsize large -text "$SMSG" &
}
export -f func_splash
if [ -s /tmp/pupcamera_ports ];then
 CAMCNT=1
 for ONEPORT in `cat /tmp/pupcamera_ports | sort -u | tr '\n' ' '`
 do
  CAM_MNT="<action>defaultfilemanager /mnt/camera${CAMCNT} & </action>"
  mkdir -p /mnt/camera${CAMCNT} #"${OPENBUTTON}"
  OPENBUTTON="${OPENBUTTON}"'
  <button space-expand="false" space-fill="false">
   '"`/usr/lib/gtkdialog/xml_button-icon open`"'
   <label>'$(gettext 'Open')' '${ONEPORT}'</label>
   <action>gphotofs --port='${ONEPORT}' /mnt/camera'${CAMCNT}'</action>
   <action>func_splash 1</action>
   '"${CAM_MNT}"'
   <action>enable:BTN_CLOSE</action>
  </button>'
  CAMCNT=$(($CAMCNT + 1))
 done
 ICON=photocamera_yes.svg
else
 OPENBUTTON='<button space-expand="false" space-fill="false">'"`/usr/lib/gtkdialog/xml_button-icon open`"'<label>'$(gettext 'Open device')'</label><sensitive>falsw</sensitive></button>'
 ICON=photocamera_no.svg
fi

[ -s /tmp/pupcamera_ports ] && MSG2="$(gettext "Click <i>Open</i> button to access files on your device. A File Manager will pop up, and if your files are there, it worked.")" || MSG=""

if [ "$ROX_FILER" ] ; then
	ROX_D1='<action>rox -D /mnt/camera1</action>'
	ROX_D2='<action>rox -D /mnt/camera2</action>'
else
	ROX_D1='<action>func_splash 2</action>'
	ROX_D2="$ROX_D1"
fi

#main gui
S='
<window title="PupCamera - '$(gettext 'Access digital camera / cellphone')'" icon-name="gtk-orientation-landscape">
<vbox>
  <frame '$(gettext 'Detected device')'>
    '"`/usr/lib/gtkdialog/xml_info scale "$ICON" 60 "${CAMERAINFO}" "${CAMERAINFO_PORT}" "${PROBEINFO}" " " "$MSG2" "$(gettext "Please click the <i>Close device</i> button when finished.")"`"' 
    <text height-request="20"><label>""</label></text>
    <hbox homogeneous="true">
      <hbox space-expand="false" space-fill="false">
        '${OPENBUTTON}'
        <button space-expand="false" space-fill="false">
          '"`/usr/lib/gtkdialog/xml_button-icon close`"'
          <label>'$(gettext 'Close device')'</label>
          <variable>BTN_CLOSE</variable>
          '"${ROX_D1}"'
          <action>umount /mnt/camera1 2>/dev/null</action>
          '"${ROX_D2}"'
          <action>umount /mnt/camera2 2>/dev/null</action>
          <sensitive>false</sensitive>
        </button>
      </hbox>
    </hbox>
    <text height-request="5"><label>""</label></text>
  </frame>

  <hbox space-expand="false" space-fill="false">
    <button>
      '"`/usr/lib/gtkdialog/xml_button-icon refresh`"'
      <label>'$(gettext 'Rescan')'</label>
      <action>EXIT:rescan</action>
    </button>
    <button>
      '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
      <label>'$(gettext 'Quit')'</label>
      <action>EXIT:finished</action>
    </button>
  </hbox>
</vbox>
</window>'
. /usr/lib/gtkdialog/xml_info gtk #build bg_pixmap for gtk-theme
export PupCamera="$S"

RETVALS="`gtkdialog -p PupCamera`"

umount /mnt/camera1 2>/dev/null #precaution.
umount /mnt/camera2 2>/dev/null #precaution.

[ "`echo "$RETVALS" | grep 'rescan'`" != "" ] && exec pupcamera #reenter.

###END###
